define(['app'], function(app) {
	'use strict';

	var PAGE_LIMIT = 20;

	var controller = function controller($scope, T_message, $window, $timeout, $ionicSlideBoxDelegate, GoPage, Auth, GoDialog,$stateParams) {
		
		$scope.isLoad = false;
		$scope.selectIndex = 0;
		
		//画面加载
		$scope.$on('$ionicView.afterEnter', function(scope, status) {
			var lan = 0; //这是状态栏，只有ios的APP才有
			if(window.cordova && window.cordova.plugins && ionic.Platform.isIOS()) {
				lan = 20;
			}
			var all = $window.innerHeight;
			$scope.myObj = {
				"height": all - 44*3 - lan + "px"
			};
			$scope.issue_type = Auth.get_loginInfo().issue_type;//1为买家  2为卖家
			$scope.init_page(0, true);
			$scope.init_page(1, true);
		}, false);
		
		$scope.$on('$ionicView.beforeEnter', function(scope, status) {
			if($stateParams.tab){//如果是0，则强制切换到“未读”
				$ionicSlideBoxDelegate.$getByHandle('tab-handle').slide($stateParams.tab);
			}
		}, false);
		
		
		$scope.data = {
			mail_count: 0,
			unread_count: 0,
			readed_count: 0,
			list: [
				{//未读
					inited: false, isend: false,
					checkedCnt: 0,
					mail_status: 0,
					cPage: 1, tPage: null,
					mails: []
				},
				{//全部
					inited: false, isend: false,
					checkedCnt: 0,
					mails: []
				}
			]
		}

		//滑动切换
		$scope.activeTab = function(index) {
			$scope.selectIndex = index;
			$ionicSlideBoxDelegate.$getByHandle('tab-handle').slide(index);
		};
        //滑动切换
		$scope.slideChanged = function(index) {
			$scope.selectIndex = index;
			var data = $scope.data.list[index];
			if (data && !data.inited) {
				$scope.init_page(index, true);
			}
		};
		
		//禁止左右滑动来切换页面1
		$scope.onTouch = function() {
			$ionicSlideBoxDelegate.$getByHandle('tab-handle').enableSlide(false);
		};
		//禁止左右滑动来切换页面2
		$scope.onRelease = function() {
			$ionicSlideBoxDelegate.$getByHandle('tab-handle').enableSlide(true);
		};
		
		//下拉刷新 判断哪个模块进行刷新
		$scope.doRefresh = function() {
			$scope.init_page($scope.selectIndex, true, 'refresh');
		};

		//加载更多
		$scope.doRefreshMore = function() {
			if ($scope.isLoad) return;
			$scope.isLoad = true;
			$scope.init_page($scope.selectIndex, false, 'more');
		};

		// 初始化页面
		$scope.init_page = function (index, isInit, completeFlag) {
			var Infos = Auth.get_loginInfo();

			if (!Infos) {
				GoDialog.toast('未登录');
				GoPage.go_tabPage('home');
				return;
			}

			var data = $scope.data.list[index];
			if (!data) {
				return;
			}

			if (isInit) data.isend = false;

			if (data.isend) return;

			var param = {
				mail_status: data.mail_status,
				pagelimit: PAGE_LIMIT,
				nPage: isInit ? 1 : (data.cPage - 0 + 1),
				kind: $scope.issue_type == 1 ? '0' : '1'// $scope.issue_type=1为买家。      kind：0：买家 1：卖家
			}
			T_message.get_list(param, function(res) {
				if (res.success != true) {
					GoDialog.toast(res.msg);
					return;
				}

				data.inited = true;
				var result = res.result;
				data.cPage = result.page.cPage;
				data.tPage = result.page.tPage;

				if (data.cPage == data.tPage) data.isend = true;

				$scope.data.mail_count = result.mail_count;
				$scope.data.unread_count = result.unread_count;
				$scope.data.readed_count = result.readed_count;


				if (param.nPage == 1) {
					data.mails = result.mails;
				} else {
					data.mails = data.mails || [];
					result.mails = result.mails || [];
					for (var i=0; i<result.mails.length; i++) {
						data.mails.push(result.mails[i]);
					} 
				}

				$scope.getMsgId();
				
			}, null, function() {
				if (completeFlag === 'refresh')	{
					$scope.$broadcast('scroll.refreshComplete');
				}
				if (completeFlag === 'more') {
					$scope.$broadcast('scroll.infiniteScrollComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 2000);
				}
			})
		}

		/**
		 * 设置选中
		 * @param {Object} isAll：是否全选
		 * index：单选的下标
		 * $event：点击事件
		 */
		$scope.setupCheck = function($event,isAll,index) {
			if($event) $event.stopPropagation();//阻止事件冒泡
			var data = $scope.data.list[$scope.selectIndex].mails;
			if (!data) return;
			if(isAll){//如果是全选
				for (var i=0; i<data.length; i++) {
					if(data[i].isCheckIcon){
						data[i].isCheckIcon = false;
					}else{
						data[i].isCheckIcon = true;
					}
				}
			}else{//单选
				if(data[index].isCheckIcon){
					data[index].isCheckIcon = false;
				}else{
					data[index].isCheckIcon = true;
				}
			}
			$scope.getMsgId();
		}
		
		//获取站内信id，同时判断是否全选
		$scope.getMsgId = function(){
			var data = $scope.data.list[$scope.selectIndex].mails;
			if(!data) return;
			var msg_ids = "";
			$scope.isCheckIconAll = true;//默认全选
			for (var i=0;i<data.length;i++) {
				if(data[i].isCheckIcon){
					msg_ids += data[i].mail_id+",";
				}else{
					$scope.isCheckIconAll = false;
				}
			}
			if(msg_ids.endsWith(",")){
				msg_ids = msg_ids.substring(0,msg_ids.length-1);
			}
			return msg_ids;
		}
		
		//删除站内信
		$scope.confirmDel = function(){
			var data = $scope.data.list[$scope.selectIndex];
			if (!data) return;
			var msg_ids = $scope.getMsgId();
			if (!msg_ids) {
				GoDialog.toast("请先选择要删除的站内信！");
				return;
			}
			GoDialog.confirm("删除站内信","确定要删除吗？",function(){
				var mail_id = msg_ids.split(",");//得到数组
				var param = {
					mail_id: mail_id,
				}
				T_message.delete(param, function(res) {
					if (res.success) {
						GoDialog.toast("删除成功！");
						$scope.init_page($scope.selectIndex, true);
					}else{
						GoDialog.toast(res.msg);
					}
				})
			})
		}
		
		
		//标为已读
		$scope.do_marked = function(){
			var data = $scope.data.list[$scope.selectIndex];
			if (!data) return;
			var msg_ids = $scope.getMsgId();
			if (!msg_ids) {
				GoDialog.toast("请先选择要标志的站内信！");
				return;
			}
			var mail_id = msg_ids.split(",");
			T_message.marked(mail_id, function(data) {
				if (data.success) {
					GoDialog.toast("标志成功！");
					$scope.init_page(0, true);
				}else{
					GoDialog.toast(data.msg);
				}
			})
		}
		

		//站内信详情
		$scope.onshow_messagedetail = function(mail_id) {
			GoPage.go_states("t-message-detail", {
				'mail_id': mail_id
			});
		}
		
	}

	controller.$inject = ['$scope', 'T_message', '$window', '$timeout', '$ionicSlideBoxDelegate','GoPage', 'Auth', 'GoDialog','$stateParams'];
	
	return app.registerController("t_messagectrl",controller);
});